package com.gooluke.mds.aspect;

import com.gooluke.mds.common.annotation.FixedDataSource;
import com.gooluke.mds.datasource.DatasourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author gooluke
 * 切换数据源切面类
 * 这个已不再使用，使用com.gooluke.aop.DataSourceAnnotationAdvisor替代
 */
@Aspect
@Component
public class DataSourceAspect {

    private static final Logger log = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 注解加在方法上
     */
    @Pointcut("@annotation(com.gooluke.mds.common.annotation.FixedDataSource)")
    private void methodPointCut() {}

    /**
     * 注解加在类上
     */
    @Pointcut("@within(com.gooluke.mds.common.annotation.FixedDataSource)")
    public void classPointcut() {}

    @Around(value = "methodPointCut() || classPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //记录当前数据源，和准备切换的数据源
        String oldDatasource = DatasourceContextHolder.getDatasource();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        java.lang.reflect.Method method = methodSignature.getMethod();

        FixedDataSource annotation = method.getAnnotation(FixedDataSource.class);
        //方法上获取注解为空，再从类上获取
        if (annotation == null) {
            annotation = method.getDeclaringClass().getAnnotation(FixedDataSource.class);
        }
        String newDatasource = annotation.value();
        //切换数据源，并执行操作
        DatasourceContextHolder.setDatasource(newDatasource);
        try {
            return joinPoint.proceed();
        } finally {
            //是否切换回初始数据源
            if (annotation.needRecover()) {
                DatasourceContextHolder.setDatasource(oldDatasource);
            }
        }
    }
}
